package com.fjwt.gz.mch.ctrl.activity;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.dto.ActivityListDTO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.ActivityChannelEntity;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.db.vo.ActivityDetailVo;
import com.fjwt.gz.db.vo.ActivityListVO;
import com.fjwt.gz.db.vo.FansActivityVO;
import com.fjwt.gz.mch.ctrl.CommonCtrl;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.*;
import com.fjwt.gz.zhyx.sms.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 活动管理
 *
 * @Author: Will
 * @Date: 2023-12-29
 * @Version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/api/activity")
public class ActivityController extends CommonCtrl {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityAwardService activityAwardService;

    @Autowired
    private ActivityChannelService activityChannelService;

    @Autowired
    private FansActivityService fansActivityService;

    /**
     * 查询活动列表
     *
     * @return
     */
    @PostMapping("/getActivityList")
    public ApiRes list() {
        ActivityListDTO activityListDTO = getObject(ActivityListDTO.class);
        String appId = request.getHeader("appid");
        activityListDTO.setAppId(appId);
        log.info("C端查询活动列表接口调用，请求地址：/api/activity/getActivityList，请求参数：{}", JSONUtil.toJsonStr(activityListDTO));
        List<ActivityListVO> list = activityService.queryListByLite(activityListDTO);
        log.info("C端查询活动列表接口调用，请求地址：/api/activity/getActivityList，返回结果：{}", JSONUtil.toJsonStr(list));
        return ApiRes.ok(list);
    }

    /**
     * 查看活动详情
     *
     * @return
     */
    @PostMapping("/details")
    public ApiRes details() {
        Long fansId = getCurrentUser().getFansId();
        Long activityId = getValLong("activityId");
        log.info("C端查看活动详情接口调用，请求地址：/api/activity/detals，请求参数：活动id：{}", activityId);
        ActivityDetailVo vo = activityService.detailByLite(activityId,fansId);
        log.info("C端查看活动详情接口调用，请求地址：/api/activity/detals，返回结果：{}", JSONUtil.toJsonStr(vo));
        ActivityDetailVo data = new ActivityDetailVo();
        BeanUtils.copyProperties(vo, data);
        return ApiRes.ok(data);
    }

    /**
     * 参与活动
     *
     * @return
     */
    @PostMapping(value = "/takePartIn")
    public ApiRes takePartIn() {
        FansActivityDTO fansActivityDTO = getObject(FansActivityDTO.class);
        fansActivityDTO.setFansId(getCurrentUser().getFansId());
        fansActivityDTO.setStartTime(System.currentTimeMillis());
        String appid = request.getHeader("appid");
        String locationAgentNo =request.getHeader("locationAgentNo");
        fansActivityDTO.setAppId(appid);
        fansActivityDTO.setLocationAgentNo(locationAgentNo);
        log.info("C端用户参加活动接口调用，请求地址：/api/activity/takePartIn，请求参数：{}", JSONUtil.toJsonStr(fansActivityDTO));
        ActivityAwardVO vo = activityService.takePartIn(fansActivityDTO);
        log.info("C端用户参加活动接口调用，请求地址：/api/activity/takePartIn，返回结果：{}", JSONUtil.toJsonStr(vo));
        return ApiRes.ok(vo);
    }

    /**
     * 查询用户活动奖品列表
     * @return
     */
    @PostMapping("/getActivityAwards")
    public ApiRes getActivityAwards(){
        FansActivityDTO fansActivityDTO = getObject(FansActivityDTO.class);
        log.info("C端查询用户活动奖品列表接口调用，请求地址：/api/activity/getActivityAwards，请求参数：{}", JSONUtil.toJsonStr(fansActivityDTO));
        fansActivityDTO.setFansId(getCurrentUser().getFansId());

        if(ObjectUtils.isEmpty(fansActivityDTO.getActivityId()) || StringUtils.isEmpty(fansActivityDTO.getActivityTemplateNo())){
            return ApiRes.customFail("网络故障，请稍后重试！");
        }

        JSONObject json = SpringBeansUtil.getBean(fansActivityDTO.getActivityTemplateNo() + "Service", BaseActivityService.class).getActivityAwards(fansActivityDTO);
        log.info("C端查询用户活动奖品列表接口调用，请求地址：/api/activity/getActivityAwards，返回结果：{}", JSONUtil.toJsonStr(json));
        return ApiRes.ok(json);
    }

    /**
     * 查询活动奖品列表
     * @return
     */
    @PostMapping("/awardList")
    public ApiRes getAwardList() {
        FansActivityDTO fansActivityDTO = getObject(FansActivityDTO.class);
        Long activityId = fansActivityDTO.getActivityId();
        log.info("C端获取活动奖品列表接口调用，请求地址：/api/activity/awardList，请求参数：{}",JSONUtil.toJsonStr(fansActivityDTO));
        if (activityId==null) {
            return ApiRes.customFail("网络故障，请稍后重试！");
        }
        List<ActivityAwardVO> activityAwardVOList = activityAwardService.queryList(activityId);
        log.info("C端获取活动奖品列表接口调用，请求地址：/api/activity/awardList，返回结果：{}",JSONUtil.toJsonStr(activityAwardVOList));
        return ApiRes.ok(activityAwardVOList);
    }


    /**
     * 查询 越减越便宜活动卡券的剩余数量
     * @return
     */
    @PostMapping("/getActivityCouponNum")
    public ApiRes getActivityCouponNum() {
        Long activityId = getValLong("activityId");
        log.info("C端查询越减越便宜活动卡券的剩余数量接口调用，请求地址：/api/activity/getActivityCouponNum，请求参数：{}", activityId);
        ActivityAwardVO vo = activityAwardService.getActivityCouponNum(activityId);
        log.info("C端查询越减越便宜活动卡券的剩余数量接口调用，请求地址：/api/activity/getActivityCouponNum，返回结果：{}", JSONUtil.toJsonStr(vo));
        return ApiRes.ok(vo);
    }


    /**
     * 查询 活动卡券的剩余数量【公共可用，目前先加卡券的类型】
     * @return
     */
    @PostMapping("/getActivityAwardNum")
    public ApiRes getActivityAwardNum() {
        Long activityId = getValLong("activityId");
        Long awardId = getValLong("awardId");
        Long awardType = getValLong("awardType");
        log.info("C端查询活动卡券的剩余数量接口调用，请求地址：/api/activity/getActivityCouponNum，请求参数:activityId：{},awardId:{},awardType:{}", activityId,awardId,awardType);
        ActivityAwardVO vo = activityAwardService.getActivityAwardNum(activityId,awardId,awardType);
        log.info("C端查询活动卡券的剩余数量接口调用，请求地址：/api/activity/getActivityCouponNum，返回结果：{}", JSONUtil.toJsonStr(vo));
        return ApiRes.ok(vo);
    }

    /**
     * 生成活动海报接口
     */
    @GetMapping("/findActivityImgUrl")
    @Transactional(rollbackFor = Exception.class)
    public ApiRes findActivityImgUrl() {
        Long channelId = getValLong("channelId");
        if(Objects.isNull(channelId)){
            return ApiRes.customFail("网络故障，请稍后重试！");
        }
        ActivityChannelEntity channelEntity = activityChannelService.findActivityImgUrlByActivityId(channelId);
        return ApiRes.ok(channelEntity);
    }

    /**
     * 查询用户参与的活动列表
     * @return
     */
    @PostMapping("/getFansActivityList")
    public ApiRes getFansActivityList() {
        Long fansId = getCurrentUser().getFansId();
        log.info("获取用户参与活动记录接口调用，请求地址：/api/activity/getFansActivityList，请求参数：用户id：{}",fansId);
        String appId = request.getHeader("appid");
        IPage<ActivityListVO> page = fansActivityService.getFansActivityList(getIPage(), fansId, appId);
        return ApiRes.page(page);
    }

    /**
     * 查询用户参与的活动列表中的详细信息
     * @return
     */
    @PostMapping("/getFansActivityDetail")
    public ApiRes getFansActivityDetail() {
        Long activityId = getValLong("activityId");
        log.info("获取用户参与的活动列表中的详细信息，请求地址：/api/activity/getFansActivityDetail，请求参数：活动id：{}",activityId);
        FansActivityVO detail = fansActivityService.getFansActivityDetail(activityId);
        JSONObject json = new JSONObject();
        json.put("detail",detail);
        return ApiRes.ok(json);
    }

    /**
     * 老客唤醒通过手机号验证参与 奖励福分 并迁移历史福分
     * @return
     */
    @PostMapping("/awakeActivityByPhone")
    public ApiRes awakeActivityByPhone(){
        String code = getValString("code");
        String phone = getValString("phone");
        Integer flag = getValInteger("flag");
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            return ApiRes.customFail("网络故障，请稍后重试！");
        }
        JSONObject smsCOde = SmsUtil.getSmsCOde(CS.SYS_ROLE_TYPE.MCH, phone, flag);
        if (smsCOde == null || !code.equals(smsCOde.getString("code"))) {
            return ApiRes.customFail("验证码错误");
        }
        FansActivityDTO fansActivityDTO = getObject(FansActivityDTO.class);
        fansActivityDTO.setFansId(getCurrentUser().getFansId());
        fansActivityDTO.setStartTime(System.currentTimeMillis());
        fansActivityDTO.setActivityTemplateNo("ACTE027");
        String appid = request.getHeader("appid");
        fansActivityDTO.setAppId(appid);
        log.info("老客唤醒通过手机号验证参与：fansId:{}, 参数：{}",getCurrentUser().getFansId(), fansActivityDTO);
        ActivityAwardVO vo = activityService.takePartIn(fansActivityDTO);
        return ApiRes.ok(vo);
    }
    /**
     * 校验是否存在引导客户实名活动
     * @return
     */
    @PostMapping("/checkActivity")
    public ApiRes checkActivity(){
        LambdaQueryWrapper<ActivityEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ActivityEntity::getActivityTemplateNo,"ACTE019");
        queryWrapper.eq(ActivityEntity::getState,4);
        ActivityEntity entity = activityService.getBaseMapper().selectOne(queryWrapper);
        return null != entity?ApiRes.ok(entity):ApiRes.ok(0);
    }

    /**
     * 用户转介列表(转介发放奖品列表)
     * @return
     */
    @PostMapping("/getActivityAwardItems")
    public ApiRes getActivityAwardItems(){
        FansActivityDTO fansActivityDTO = getObject(FansActivityDTO.class);
        if(ObjectUtils.isEmpty(fansActivityDTO.getActivityTemplateNo()) || ObjectUtils.isEmpty(fansActivityDTO.getAwardId()) || ObjectUtils.isEmpty(fansActivityDTO.getAwardType())){
            return ApiRes.customFail("网络故障，请稍后重试！");
        }
        fansActivityDTO.setFansId(getCurrentUser().getFansId());
        fansActivityDTO.setAppId(getCurrentUser().getAppId());
        List<FansAwardEntity> list = SpringBeansUtil.getBean(fansActivityDTO.getActivityTemplateNo() + "Service", BaseActivityService.class).getActivityAwardItems(fansActivityDTO);
        return ApiRes.ok(list);
    }


    /**
     * 商户抽奖可用次数
     * @return
     */
    @RequestMapping(value = "/awardTimes", method = RequestMethod.POST)
    public ApiRes getAwardTimes() {
        FansActivityDTO fansActivityDTO = getObject(FansActivityDTO.class);
        Long activityId = fansActivityDTO.getActivityId();
        fansActivityDTO.setFansId(getCurrentUser().getFansId());
        log.info("获取商户可抽奖次数接口调用，请求地址：/api/activity/awardTimes，请求参数：{}",JSONUtil.toJsonStr(fansActivityDTO));
        if (activityId==null) {
            return ApiRes.customFail("网络故障，请稍后重试！");
        }
        int times = activityService.getFansAwardTimes(fansActivityDTO);
        return ApiRes.ok(times);
//        if(TextUtils.isEmpty(mchNo)){
//            return  ApiRes.ok(activityService.getFansAwardTimes(activityId,fansId));
//        }else {
//            return  ApiRes.ok( activityService.getMchAwardTimes(activityId,mchNo));
//        }
    }

    /**
     * 根据渠道号查询活动列表
     */
    @PostMapping("/getActivityByChannelCode")
    @Transactional(rollbackFor = Exception.class)
    public ApiRes getActivityByChannelCode(){
        String channelCode = getValString("channelCode");
        Integer channelType = getValInteger("channelType");
        if (StringUtils.isEmpty(channelCode) || null == channelType){
            throw new BizException("网络故障，请稍后重试！");
        }
        log.info("根据渠道号查询活动列表，请求地址：/api/activity/getActivityByChannelCode，请求参数：channelCode:{},channelType:{}", channelCode, channelType);
        List<ActivityEntity> activityEntity = activityService.selectActivityListByChannelType(channelCode, channelType);

        JSONObject json = new JSONObject();
        json.put("list",activityEntity);
        return ApiRes.ok(json);
    }

}

